<template>
  <div class="app-container">
    <div class="tops">
      <div v-for="(value, index) in lists" :key="index" class="list">
        <div class="list_left">
          <div>{{ value.name }}</div>
          <div>
            <span>{{ value.num }}</span>
            <span>{{ value.unit }}</span>
          </div>
        </div>
        <div class="list_right">
          <img :src="value.imgs" alt="">
        </div>
      </div>
    </div>
    <div class="centers">
      <div class="titles">
        <div v-for="(value, index) in titleLists" :class="index == selectIndexs ? 'selectIndex' : ''" :key="index"
          class="titleLists" @click="changeSearchs(index)">
          {{ value }}
        </div>
      </div>
      <div class="searchParams">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
          <el-form-item label="仓库名称" prop="warehouseName">
            <el-select style="width: 250px;" v-model="queryParams.warehouseCode">
              <el-option v-for="(value, index) in warehouseData" :key="index" :label="value.warehouseName"
                :value="value.warehouseCode"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备件名称" prop="warehouseName">
            <el-input style="width: 250px;" v-model="queryParams.warehouseName" placeholder="请输入" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="备件编码" prop="orderNo">
            <el-input style="width:250px;" v-model="queryParams.orderNo" placeholder="请输入" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="drawFooter" v-if="selectIndexs == 0">
        <div class="drawLeft">
          <div class="stock-container">
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/dqkc.png" alt="当前库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">当前库存</div>
                <div class="stock-value">
                  <span>{{ totalStock }}</span>
                  <span>台</span>
                </div>
              </div>
            </div>
            <div class="divider"></div>
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/aqkc.png" alt="安全库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">安全库存</div>
                <div class="stock-value"> <span>{{ totalSafeStock }}</span><span>台</span></div>
              </div>
            </div>
          </div>
          <div class="leftHeader">
            <div>库存明细</div>
          </div>
          <div class="leftTableWrap">
            <el-table :data="inventoryTableData" size="small" :max-height="rightHeight">
              <el-table-column prop="partName" label="备件名称" min-width="120" :show-overflow-tooltip="true"
                key="partName"></el-table-column>
              <el-table-column prop="realStock" key="realStock" label="在库数量" align="center"></el-table-column>
              <el-table-column prop="safeStock" key="safeStock" label="安全库存" align="center"></el-table-column>
              <el-table-column prop="status" label="状态" align="center" key="status">
                <template slot-scope="scope">
                  <div v-if="scope.row.status == 0">正常</div>
                  <div v-if="scope.row.status == 1">缺货</div>
                </template>
              </el-table-column>
            </el-table>
          </div>

        </div>

        <div class="drawRight">
          <div class="chart-container">
            <div ref="barChart" class="chart"></div>
          </div>
          <div class="pie-charts">
            <div class="chart-container">
              <div ref="pieChart1" class="chart"></div>
              <div class="chartTitle">各型号备件数量</div>
            </div>
            <div class="chart-container">
              <div ref="pieChart2" class="chart"></div>
              <div class="chartTitle">各型号备件数量</div>
            </div>
          </div>
        </div>
      </div>

      <div class="drawFooter" v-if="selectIndexs == 1">
        <div class="drawLeft">
          <div class="stock-container">
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/dqkc.png" alt="当前库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">领用数</div>
                <div class="stock-value">
                  <span>{{ totalcount }}</span>
                  <span>台</span>
                </div>
              </div>
            </div>
            <div class="divider"></div>
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/aqkc.png" alt="安全库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">领用总金额</div>
                <div class="stock-value"> <span>{{ totalamount }}</span><span>万元</span></div>
              </div>
            </div>
          </div>
          <div class="leftHeader">
            <div>领用明细</div>
          </div>
          <div class="leftTableWrap">
            <el-table :data="inventoryTableData1" size="small" :max-height="rightHeight">
              <el-table-column prop="deptname" min-width="120" :show-overflow-tooltip="true" label="部门名称" align="center"
                key="deptname1"></el-table-column>
              <el-table-column prop="username" key="username1" label="领用人" align="center"></el-table-column>
              <el-table-column prop="totalquantity" key="totalquantity1" label="领用数量" align="center"> </el-table-column>
              <el-table-column prop="totalamount" key="totalamount1" label="领用金额" align="center"> </el-table-column>
              <el-table-column prop="usetimes" key="usetimes1" label="领用次数" align="center"></el-table-column>
            </el-table>
          </div>
        </div>
        <div class="drawRight">
          <div class="chart-container">
            <div ref="barChart1" class="chart"></div>
          </div>
          <div class="pie-charts">
            <div class="chart-container">
              <div ref="pieChart3" class="chart"></div>
              <div class="chartTitle">各部门领用数量</div>
            </div>
            <div class="chart-container">
              <div ref="pieChart4" class="chart"></div>
              <div class="chartTitle">各部门领用金额</div>
            </div>
          </div>
        </div>
      </div>


      <div class="drawFooter" v-if="selectIndexs == 2">
        <div class="drawLeft">
          <div class="stock-container">
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/dqkc.png" alt="当前库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">入库数</div>
                <div class="stock-value">
                  <span>{{ totalcount1 }}</span>
                  <span>台</span>
                </div>
              </div>
            </div>
            <div class="divider"></div>
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/aqkc.png" alt="安全库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">入库总金额</div>
                <div class="stock-value"> <span>{{ totalamount1 }}</span><span>万元</span></div>
              </div>
            </div>
          </div>
          <div class="leftHeader">
            <div>入库明细</div>
          </div>
          <div class="leftTableWrap">
            <el-table :data="inventoryTableData2" size="small" :max-height="rightHeight">
              <el-table-column prop="partname" label="备件名称" min-width="120" :show-overflow-tooltip="true"
                key="partname2"></el-table-column>
              <el-table-column prop="quantity" key="quantity12" label="数量" align="center"></el-table-column>
              <el-table-column prop="unitprice" key="unitprice2" label="单价" align="center"></el-table-column>
              <el-table-column prop="totalprice" key="totalprice2" label="总价" align="center"></el-table-column>
            </el-table>
          </div>
        </div>
        <div class="drawRight">
          <div class="chart-container">
            <div ref="barChart2" class="chart"></div>
          </div>
          <div class="pie-charts">
            <div class="chart-container">
              <div ref="pieChart5" class="chart"></div>
              <div class="chartTitle">入库数量</div>
            </div>
            <div class="chart-container">
              <div ref="pieChart6" class="chart"></div>
              <div class="chartTitle">入库总金额</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import zksl from '../assets/images/zksl.png'
import zkze from '../assets/images/zkze.png'
import zqk from '../assets/images/zqk.png'
import lysl from '../assets/images/lysl.png'
import { warehouseLists } from '@/api/select.js'
import * as echarts from 'echarts';
import { inSummary, modelQuantityPie, modelAmountPie, inProductStat, detailSimple, homesummary, deptcount, deptamount, productstat, homedetail, distributionstock, distributionassets, totalStocks, totalSafeStocks, totalQuantity, stockcount, stockamount, stockgap, getPartStats, getpartList } from '@/api/home.js'
export default {
  name: "homeIndex",
  data() {
    return {
      inventoryTableData2: [],
      totalcount1: 0,
      totalamount1: 0,
      inventoryTableData1: [],
      totalSafeStock: 0,
      totalStock: 0,
      selectIndexs: 0,
      rightHeight: 0,   // 右侧可用高度
      inventoryTableData: [],
      barChartData2: {
        months: [],
        stockTotal: [],
        assetTotal: []
      },
      barChartData1: {
        months: [],
        stockTotal: [],
        assetTotal: []
      },
      barChartData: {
        months: [],
        stockTotal: [],
        assetTotal: []
      },
      pieChartData2: [
        {
          name: '各型号入库数量',
          data: [

          ],
          unit: '台'
        },
        {
          name: '各型号入库金额',
          data: [

          ],
          unit: '万元'
        }
      ],
      pieChartData1: [
        {
          name: '各部门领用数量',
          data: [

          ],
          unit: '台'
        },
        {
          name: '各部门领用金额',
          data: [

          ],
          unit: '万元'
        }
      ],
      pieChartData: [
        {
          name: '各型号备件数量',
          data: [

          ],
          unit: '台'
        },
        {
          name: '各型号备件金额',
          data: [

          ],
          unit: '万元'
        }
      ],
      warehouseData: [],
      queryParams: {},
      titleLists: ["库存分析", "领用分析", "入库分析"],
      lists: [
        { name: '在库数量', num: 100, unit: '台', imgs: zksl },
        { name: '在库总额', num: 100, unit: '万元', imgs: zkze },
        { name: '总缺口', num: 100, unit: '台', imgs: zqk },
        { name: '领用数量', num: 100, unit: '台', imgs: lysl }
      ],
      totalcount: 0,
      totalamount: 0,
    }
  },
  created() {
    this.loadWarehouseData()
    this.partList()
    stockcount().then(res => {
      this.lists[0].num = res.data
    })
    stockamount().then(res => {
      this.lists[1].num = res.data
    })
    stockgap().then(res => {
      this.lists[2].num = res.data
    })
    totalQuantity().then(res => {
      this.lists[3].num = res.data
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calcHeight);
  },
  mounted() {
    this.$nextTick(() => {
      this.initBarChart();
      this.initPieCharts();
      this.calcHeight();
      this.gettotalStock();
      this.gettotalSafeStocks();
      window.addEventListener('resize', this.calcHeight);
    });
  },
  methods: {
    gettotalStock() {
      totalStocks(this.queryParams).then(res => {
        this.totalStock = res.data
      })
    },
    gettotalSafeStocks() {
      totalSafeStocks(this.queryParams).then(res => {
        this.totalSafeStock = res.data
      })
    },
    changeSearchs(index) {
      this.selectIndexs = index
      if (this.selectIndexs == 0) {
        this.initBarChart();
        this.initPieCharts();
        this.gettotalStock();
        this.gettotalSafeStocks();
        this.partList()
      } else if (this.selectIndexs == 1) {
        this.gethomesummary()
        this.gethomedetail()
        this.initBarChart1()
        this.initPieCharts1();
      } else if (this.selectIndexs == 2) {
        this.getinSummary()
        this.getdetailSimple()
        this.initBarChart2()
        this.initPieCharts2();
      }
      this.calcHeight();
    },
    initBarChart2() {
      inProductStat(this.queryParams).then(res => {
        let datas = res.data

        this.barChartData1.months = datas.map(item => item.partname)
        this.barChartData1.assetTotal = datas.map(item => item.totalamount)
        this.barChartData1.stockTotal = datas.map(item => item.totalcount)
        if (!this.$refs.barChart3) return;
        const chart3 = echarts.init(this.$refs.barChart3);
        const option = {
          tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
          legend: {
            data: ['入库数量', '入库总额'],
            textStyle: { fontSize: 12 },
            center: 'center',
            top: 0,
            icon: 'circle',   // ← 关键：图例图标变圆形
            itemWidth: 12,    // 圆点直径（可选）
            itemHeight: 12
          },
          grid: { left: '5%', right: '5%', bottom: '0%', top: '20%', containLabel: true },
          xAxis: {
            type: 'category',
            data: this.barChartData2.months,
            axisLabel: { fontSize: 10, interval: 0 }
          },
          yAxis: [
            { type: 'value', name: '件', min: 0, max: 2500, interval: 500, axisLabel: { fontSize: 10 } },
            {
              type: 'value',
              name: '万元',
              min: 0,
              max: 500,
              interval: 50,
              position: 'right',
              axisLabel: { fontSize: 10 },
              axisLine: { show: false }
            }
          ],
          series: [
            {
              name: '入库总数',
              type: 'bar',
              data: this.barChartData2.stockTotal,
              barWidth: 14,                     // 宽度 14px
              itemStyle: {
                borderRadius: [20, 20, 0, 0],   // 上下圆角 20px
                color: {
                  type: 'linear',
                  x: 0, y: 0, x2: 0, y2: 1,
                  colorStops: [
                    { offset: 0, color: '#C8AEFC' },
                    { offset: 1, color: '#9463F7' }
                  ]
                }
              }
            },
            {
              name: '入库总额',
              type: 'line',
              yAxisIndex: 1,
              data: this.barChartData2.assetTotal,
              lineStyle: { color: '#20C997', width: 2 },
              symbol: 'none',
              itemStyle: { color: '#20C997' }
            }
          ]
        };
        chart3.setOption(option);
        window.addEventListener('resize', () => chart3.resize());
      })

    },
    initPieCharts2() {
      modelQuantityPie(this.queryParams).then(res => {
        let data = []
        res.data.forEach(element => {
          data.push({
            name: element.model,
            value: element.totalcount
          })
        });
        this.pieChartData2[0].data = data
        this.getPieCharts5()
      })
      modelAmountPie(this.queryParams).then(res => {
        let data = []
        res.data.forEach(element => {
          data.push({
            name: element.model,
            value: element.totalamount
          })
        });
        this.pieChartData2[1].data = data
        this.getPieCharts6()
      })

    },
    getPieCharts5() {
      if (!this.$refs.pieChart5) return;
      const pie5 = echarts.init(this.$refs.pieChart5);

      const getPieOption = (data, unit) => {
        // 定义前 4 个扇区的渐变色（从下往上 0deg）
        const gradList = [
          [
            { offset: 0, color: '#FAB2FF' },
            { offset: 1, color: '#5644FF' }
          ],
          [
            { offset: 0, color: '#FEA492' },
            { offset: 1, color: '#FF4C52' }
          ],
          [
            { offset: 0, color: '#7AECF8' },
            { offset: 1, color: '#48DE94' }
          ],
          [
            { offset: 0, color: '#A5A1FF' },
            { offset: 1, color: '#1F90FF' }
          ]
        ];

        const showData = data.map((d, i) => {
          const color =
            i < 4
              ? {
                type: 'linear',
                x: 0,
                y: 1,
                x2: 0,
                y2: 0, // 0deg 从下往上
                colorStops: gradList[i]
              }
              : ['#FFDD65', '#B37FEB', '#4ECBFF'][i - 4];

          return { ...d, itemStyle: { color } };
        });

        return {
          tooltip: { trigger: 'item', formatter: '{b}: {c}' + unit },
          legend: { show: false },
          series: [{
            type: 'pie',
            // radius: '50%',
            radius: ['0%', '70%'],
            // roseType: 'radius',
            // center: ['50%', '50%'],
            data: showData,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{c}' + unit,
              fontSize: 11,
              lineHeight: 14
            },
            labelLine: { length: 10, length2: 15 }
          }]
        };
      };

      pie5.setOption(getPieOption(this.pieChartData2[0].data, this.pieChartData2[0].unit));
      // pie2.setOption(getPieOption(this.pieChartData[1].data, this.pieChartData[1].unit));

      window.addEventListener('resize', () => { pie5.resize() });
    },
    getPieCharts6() {
      if (!this.$refs.pieChart6) return;
      const pie6 = echarts.init(this.$refs.pieChart6);

      const getPieOption = (data, unit) => {
        // 定义前 4 个扇区的渐变色（从下往上 0deg）
        const gradList = [
          [
            { offset: 0, color: '#FAB2FF' },
            { offset: 1, color: '#5644FF' }
          ],
          [
            { offset: 0, color: '#FEA492' },
            { offset: 1, color: '#FF4C52' }
          ],
          [
            { offset: 0, color: '#7AECF8' },
            { offset: 1, color: '#48DE94' }
          ],
          [
            { offset: 0, color: '#A5A1FF' },
            { offset: 1, color: '#1F90FF' }
          ]
        ];

        const showData = data.map((d, i) => {
          const color =
            i < 4
              ? {
                type: 'linear',
                x: 0,
                y: 1,
                x2: 0,
                y2: 0, // 0deg 从下往上
                colorStops: gradList[i]
              }
              : ['#FFDD65', '#B37FEB', '#4ECBFF'][i - 4];

          return { ...d, itemStyle: { color } };
        });

        return {
          tooltip: { trigger: 'item', formatter: '{b}: {c}' + unit },
          legend: { show: false },
          series: [{
            type: 'pie',
            // radius: '50%',
            radius: ['0%', '70%'],
            // roseType: 'radius',
            // center: ['50%', '50%'],
            data: showData,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{c}' + unit,
              fontSize: 11,
              lineHeight: 14
            },
            labelLine: { length: 10, length2: 15 }
          }]
        };
      };

      pie6.setOption(getPieOption(this.pieChartData2[1].data, this.pieChartData2[1].unit));
      // pie2.setOption(getPieOption(this.pieChartData[1].data, this.pieChartData[1].unit));

      window.addEventListener('resize', () => { pie6.resize() });
    },
    getdetailSimple() {
      detailSimple(this.queryParams).then(res => {
        this.inventoryTableData2 = res.data
      })
    },
    initPieCharts1() {
      deptcount(this.queryParams).then(res => {
        let data = []
        res.data.forEach(element => {
          data.push({
            name: element.deptname,
            value: element.totalcount
          })
        });
        this.pieChartData1[0].data = data
        this.getPieCharts3()
      })
      deptamount(this.queryParams).then(res => {
        let data = []
        res.data.forEach(element => {
          data.push({
            name: element.deptname,
            value: element.totalamount
          })
        });
        this.pieChartData1[1].data = data
        this.getPieCharts4()
      })

    },
    getPieCharts3() {
      if (!this.$refs.pieChart3) return;
      const pie3 = echarts.init(this.$refs.pieChart3);

      const getPieOption = (data, unit) => {
        // 定义前 4 个扇区的渐变色（从下往上 0deg）
        const gradList = [
          [
            { offset: 0, color: '#FAB2FF' },
            { offset: 1, color: '#5644FF' }
          ],
          [
            { offset: 0, color: '#FEA492' },
            { offset: 1, color: '#FF4C52' }
          ],
          [
            { offset: 0, color: '#7AECF8' },
            { offset: 1, color: '#48DE94' }
          ],
          [
            { offset: 0, color: '#A5A1FF' },
            { offset: 1, color: '#1F90FF' }
          ]
        ];

        const showData = data.map((d, i) => {
          const color =
            i < 4
              ? {
                type: 'linear',
                x: 0,
                y: 1,
                x2: 0,
                y2: 0, // 0deg 从下往上
                colorStops: gradList[i]
              }
              : ['#FFDD65', '#B37FEB', '#4ECBFF'][i - 4];

          return { ...d, itemStyle: { color } };
        });

        return {
          tooltip: { trigger: 'item', formatter: '{b}: {c}' + unit },
          legend: { show: false },
          series: [{
            type: 'pie',
            // radius: '50%',
            radius: ['0%', '70%'],
            // roseType: 'radius',
            // center: ['50%', '50%'],
            data: showData,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{c}' + unit,
              fontSize: 11,
              lineHeight: 14
            },
            labelLine: { length: 10, length2: 15 }
          }]
        };
      };

      pie3.setOption(getPieOption(this.pieChartData1[0].data, this.pieChartData1[0].unit));
      // pie2.setOption(getPieOption(this.pieChartData[1].data, this.pieChartData[1].unit));

      window.addEventListener('resize', () => { pie3.resize() });
    },
    getPieCharts4() {
      if (!this.$refs.pieChart4) return;
      const pie4 = echarts.init(this.$refs.pieChart4);

      const getPieOption = (data, unit) => {
        // 定义前 4 个扇区的渐变色（从下往上 0deg）
        const gradList = [
          [
            { offset: 0, color: '#FAB2FF' },
            { offset: 1, color: '#5644FF' }
          ],
          [
            { offset: 0, color: '#FEA492' },
            { offset: 1, color: '#FF4C52' }
          ],
          [
            { offset: 0, color: '#7AECF8' },
            { offset: 1, color: '#48DE94' }
          ],
          [
            { offset: 0, color: '#A5A1FF' },
            { offset: 1, color: '#1F90FF' }
          ]
        ];

        const showData = data.map((d, i) => {
          const color =
            i < 4
              ? {
                type: 'linear',
                x: 0,
                y: 1,
                x2: 0,
                y2: 0, // 0deg 从下往上
                colorStops: gradList[i]
              }
              : ['#FFDD65', '#B37FEB', '#4ECBFF'][i - 4];

          return { ...d, itemStyle: { color } };
        });

        return {
          tooltip: { trigger: 'item', formatter: '{b}: {c}' + unit },
          legend: { show: false },
          series: [{
            type: 'pie',
            // radius: '50%',
            radius: ['0%', '70%'],
            // roseType: 'radius',
            // center: ['50%', '50%'],
            data: showData,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{c}' + unit,
              fontSize: 11,
              lineHeight: 14
            },
            labelLine: { length: 10, length2: 15 }
          }]
        };
      };

      pie4.setOption(getPieOption(this.pieChartData1[1].data, this.pieChartData1[1].unit));
      // pie2.setOption(getPieOption(this.pieChartData[1].data, this.pieChartData[1].unit));

      window.addEventListener('resize', () => { pie4.resize() });
    },
    gethomedetail() {
      homedetail(this.queryParams).then(res => {
        this.inventoryTableData1 = res.data
      })
    },
    getinSummary() {
      inSummary(this.queryParams).then(res => {
        this.totalcount1 = res.data.total_count
        this.totalamount1 = res.data.total_amount
      })
    },
    gethomesummary() {
      homesummary(this.queryParams).then(res => {
        this.totalcount = res.data.totalcount
        this.totalamount = res.data.totalamount
      })
    },
    initBarChart1() {
      productstat(this.queryParams).then(res => {
        let datas = res.data

        this.barChartData1.months = datas.map(item => item.partname)
        this.barChartData1.assetTotal = datas.map(item => item.totalamount)
        this.barChartData1.stockTotal = datas.map(item => item.totalcount)
        if (!this.$refs.barChart1) return;
        const chart1 = echarts.init(this.$refs.barChart1);
        const option = {
          tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
          legend: {
            data: ['领用数量', '领用总额'],
            textStyle: { fontSize: 12 },
            center: 'center',
            top: 0,
            icon: 'circle',   // ← 关键：图例图标变圆形
            itemWidth: 12,    // 圆点直径（可选）
            itemHeight: 12
          },
          grid: { left: '5%', right: '5%', bottom: '0%', top: '20%', containLabel: true },
          xAxis: {
            type: 'category',
            data: this.barChartData1.months,
            axisLabel: { fontSize: 10, interval: 0 }
          },
          yAxis: [
            { type: 'value', name: '件', min: 0, max: 2500, interval: 500, axisLabel: { fontSize: 10 } },
            {
              type: 'value',
              name: '万元',
              min: 0,
              max: 500,
              interval: 50,
              position: 'right',
              axisLabel: { fontSize: 10 },
              axisLine: { show: false }
            }
          ],
          series: [
            {
              name: '领用总数',
              type: 'bar',
              data: this.barChartData1.stockTotal,
              barWidth: 14,                     // 宽度 14px
              itemStyle: {
                borderRadius: [20, 20, 0, 0],   // 上下圆角 20px
                color: {
                  type: 'linear',
                  x: 0, y: 0, x2: 0, y2: 1,
                  colorStops: [
                    { offset: 0, color: '#C8AEFC' },
                    { offset: 1, color: '#9463F7' }
                  ]
                }
              }
            },
            {
              name: '领用总额',
              type: 'line',
              yAxisIndex: 1,
              data: this.barChartData1.assetTotal,
              lineStyle: { color: '#20C997', width: 2 },
              symbol: 'none',
              itemStyle: { color: '#20C997' }
            }
          ]
        };
        chart1.setOption(option);
        window.addEventListener('resize', () => chart1.resize());
      })

    },
    partList() {
      getpartList(this.queryParams).then(res => {
        this.inventoryTableData = res.rows
      })
    },
    loadAllData() {
      if (this.selectIndexs == 0) {
        this.initBarChart();
        this.initPieCharts();
        this.gettotalStock();
        this.gettotalSafeStocks();
        this.partList()
      } else if (this.selectIndexs == 1) {
        this.gethomesummary()
        this.initBarChart1()
        this.initPieCharts1();
        this.gethomedetail()
      } else if (this.selectIndexs == 2) {
        this.getinSummary()
        this.getdetailSimple()
        this.initBarChart2()
        this.initPieCharts2();
      }
      this.calcHeight();
    },
    handleQuery() {
      this.loadAllData()
    },
    resetQuery() {
      this.queryParams = {
        warehouseCode: '',
        partName: '',
        partCode: ''
      }
      this.loadAllData()
    },
    calcHeight() {
      // 整个右侧容器高度
      const drawRight = this.$el.querySelector('.drawRight');
      // 右侧顶部标题 + 搜索区高度（没有就删掉）
      const titles = this.$el.querySelector('.titles');
      const search = this.$el.querySelector('.searchParams');
      const pad = 16;   // drawRight 上下 padding 各 16
      let headH = 0;
      if (titles) headH += titles.offsetHeight;
      if (search) headH += search.offsetHeight;
      // 可用高度 = 右侧总高 - 头 - 上下 padding
      this.rightHeight = drawRight.offsetHeight - headH - pad * 2;
    },
    initBarChart() {
      getPartStats(this.queryParams).then(res => {
        let datas = res.data

        this.barChartData.months = datas.map(item => item.part_name)
        this.barChartData.assetTotal = datas.map(item => item.total_amount)
        this.barChartData.stockTotal = datas.map(item => item.total_quantity)
        if (!this.$refs.barChart) return;
        const chart = echarts.init(this.$refs.barChart);
        const option = {
          tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
          legend: {
            data: ['库存总数', '资产总额'],
            textStyle: { fontSize: 12 },
            center: 'center',
            top: 0,
            icon: 'circle',   // ← 关键：图例图标变圆形
            itemWidth: 12,    // 圆点直径（可选）
            itemHeight: 12
          },
          grid: { left: '5%', right: '5%', bottom: '0%', top: '20%', containLabel: true },
          xAxis: {
            type: 'category',
            data: this.barChartData.months,
            axisLabel: { fontSize: 10, interval: 0 }
          },
          yAxis: [
            { type: 'value', name: '件', min: 0, max: 2500, interval: 500, axisLabel: { fontSize: 10 } },
            {
              type: 'value',
              name: '万元',
              min: 0,
              max: 500,
              interval: 50,
              position: 'right',
              axisLabel: { fontSize: 10 },
              axisLine: { show: false }
            }
          ],
          series: [
            {
              name: '库存总数',
              type: 'bar',
              data: this.barChartData.stockTotal,
              barWidth: 14,                     // 宽度 14px
              itemStyle: {
                borderRadius: [20, 20, 0, 0],   // 上下圆角 20px
                color: {
                  type: 'linear',
                  x: 0, y: 0, x2: 0, y2: 1,
                  colorStops: [
                    { offset: 0, color: '#C8AEFC' },
                    { offset: 1, color: '#9463F7' }
                  ]
                }
              }
            },
            {
              name: '资产总额',
              type: 'line',
              yAxisIndex: 1,
              data: this.barChartData.assetTotal,
              lineStyle: { color: '#20C997', width: 2 },
              symbol: 'none',
              itemStyle: { color: '#20C997' }
            }
          ]
        };
        chart.setOption(option);
        window.addEventListener('resize', () => chart.resize());
      })

    },
    getPieCharts2() {
      if (!this.$refs.pieChart2) return;
      const pie2 = echarts.init(this.$refs.pieChart2);

      const getPieOption = (data, unit) => {
        // 定义前 4 个扇区的渐变色（从下往上 0deg）
        const gradList = [
          [
            { offset: 0, color: '#FAB2FF' },
            { offset: 1, color: '#5644FF' }
          ],
          [
            { offset: 0, color: '#FEA492' },
            { offset: 1, color: '#FF4C52' }
          ],
          [
            { offset: 0, color: '#7AECF8' },
            { offset: 1, color: '#48DE94' }
          ],
          [
            { offset: 0, color: '#A5A1FF' },
            { offset: 1, color: '#1F90FF' }
          ]
        ];

        const showData = data.map((d, i) => {
          const color =
            i < 4
              ? {
                type: 'linear',
                x: 0,
                y: 1,
                x2: 0,
                y2: 0, // 0deg 从下往上
                colorStops: gradList[i]
              }
              : ['#FFDD65', '#B37FEB', '#4ECBFF'][i - 4];

          return { ...d, itemStyle: { color } };
        });

        return {
          tooltip: { trigger: 'item', formatter: '{b}: {c}' + unit },
          legend: { show: false },
          series: [{
            type: 'pie',
            // radius: '50%',
            radius: ['0%', '70%'],
            // roseType: 'radius',
            // center: ['50%', '50%'],
            data: showData,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{c}' + unit,
              fontSize: 11,
              lineHeight: 14
            },
            labelLine: { length: 10, length2: 15 }
          }]
        };
      };

      pie2.setOption(getPieOption(this.pieChartData[1].data, this.pieChartData[1].unit));

      window.addEventListener('resize', () => { pie2.resize(); });
    },
    getPieCharts1() {
      if (!this.$refs.pieChart1) return;
      const pie1 = echarts.init(this.$refs.pieChart1);

      const getPieOption = (data, unit) => {
        // 定义前 4 个扇区的渐变色（从下往上 0deg）
        const gradList = [
          [
            { offset: 0, color: '#FAB2FF' },
            { offset: 1, color: '#5644FF' }
          ],
          [
            { offset: 0, color: '#FEA492' },
            { offset: 1, color: '#FF4C52' }
          ],
          [
            { offset: 0, color: '#7AECF8' },
            { offset: 1, color: '#48DE94' }
          ],
          [
            { offset: 0, color: '#A5A1FF' },
            { offset: 1, color: '#1F90FF' }
          ]
        ];

        const showData = data.map((d, i) => {
          const color =
            i < 4
              ? {
                type: 'linear',
                x: 0,
                y: 1,
                x2: 0,
                y2: 0, // 0deg 从下往上
                colorStops: gradList[i]
              }
              : ['#FFDD65', '#B37FEB', '#4ECBFF'][i - 4];

          return { ...d, itemStyle: { color } };
        });

        return {
          tooltip: { trigger: 'item', formatter: '{b}: {c}' + unit },
          legend: { show: false },
          series: [{
            type: 'pie',
            // radius: '50%',
            radius: ['0%', '70%'],
            // roseType: 'radius',
            // center: ['50%', '50%'],
            data: showData,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{c}' + unit,
              fontSize: 11,
              lineHeight: 14
            },
            labelLine: { length: 10, length2: 15 }
          }]
        };
      };

      pie1.setOption(getPieOption(this.pieChartData[0].data, this.pieChartData[0].unit));
      // pie2.setOption(getPieOption(this.pieChartData[1].data, this.pieChartData[1].unit));

      window.addEventListener('resize', () => { pie1.resize() });
    },

    initPieCharts() {
      distributionstock(this.queryParams).then(res => {
        let data = []
        res.data.forEach(element => {
          data.push({
            name: element.part_name,
            value: element.total_stock
          })
        });
        this.pieChartData[0].data = data
        this.getPieCharts1()
      })
      distributionassets(this.queryParams).then(res => {
        let data = []
        res.data.forEach(element => {
          data.push({
            name: element.part_name,
            value: element.total_price
          })
        });
        this.pieChartData[1].data = data
        this.getPieCharts2()
      })

    },

    loadWarehouseData() {
      warehouseLists().then(res => { this.warehouseData = res.rows || []; })
        .catch(err => { this.$message.error('加载仓库数据失败'); });
    },
  }
}
</script>

<style scoped lang="scss">
/* 全局样式 */
.app-container {
  padding: 16px;
  background: #f5f5f5;
  // min-height: 100vh;
  height: 100%;
  box-sizing: border-box;
}

/* ==== 恢复原始样式：tops ==== */
.tops {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;

  .list {
    background: #fff;
    width: 25%;
    height: 92px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .list_right {
      width: 52px;
      height: 52px;
      margin-right: 39px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .list_left {
      margin-left: 49px;

      >div:first-child {
        font-family: PingFang SC;
        font-weight: 400;
        font-size: 14px;
        line-height: 22px;
        color: rgba(0, 0, 0, 0.6);
      }

      >div:last-child {
        margin-top: 4px;

        >span:first-child {
          font-weight: 500;
          font-size: 24px;
          color: rgba(29, 37, 47, 1);
        }

        >span:last-child {
          font-weight: 400;
          font-size: 14px;
          margin-left: 4px;
          color: rgba(0, 0, 0, 0.35);
        }
      }
    }
  }
}

/* ==== 恢复原始样式：centers ==== */
.centers {
  display: flex;
  margin-top: 16px;
  flex-direction: column;
  height: calc(100vh - 190px);
  background: #fff;
  width: 100%;
  padding: 16px 0;
  /* 恢复原始padding */
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .titles {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 296px;
    height: 38px;
    line-height: 38px;
    margin: 0 auto;
    background: rgba(244, 244, 246, 1);

    .titleLists {
      width: 92px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 15px;
      color: rgba(49, 61, 75, 1);
      cursor: pointer;
    }

    .selectIndex {
      background: #fff;
      color: rgba(65, 167, 114, 1);
      border-radius: 2px;
    }
  }

  .searchParams {
    margin: 22px 0;
    /* 恢复原始margin */
    padding: 0 24px;
  }
}

/* 核心区域：drawFooter（保持之前修改的无padding） */
.drawFooter {
  display: flex;
  gap: 16px;
  flex: 1;
  /* 占满父级剩余高度 */
  min-height: 0;
  /* 关键：允许继续压缩，防止溢出截断 */
  height: auto !important;
  /* 放弃之前的 calc 写法，交给 flex 控制 */

}

/* 左侧：库存明细 */
.drawLeft {
  width: 40%;
  background: #fff;
  padding: 0 16px 16px;
  display: flex;
  flex-direction: column;
  /* 关键 */
  height: 100%;
  /* 与右侧等高 */
  box-sizing: border-box;
}

.leftTableWrap {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.el-table {
  // flex: 1;                  /* 表格本身也 flex:1，自然撑高 */
  width: 100%;
}

/* 统计卡片 */
.stock-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f8f8f8;
  border-radius: 8px;
  padding: 12px 78px;

  .stock-card {
    flex: 0 0 auto;
    /* 不改变原有宽度 */
    display: flex;
    align-items: center;
  }

  .icon-wrapper {
    width: 28px;
    height: 28px;
    margin-right: 10px;
  }

  .text-content {
    margin-left: 5px;

    .stock-label {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.6);
    }

    .stock-value {
      margin-top: 4px;

      >span:first-child {
        font-size: 16px;
        color: #000;
      }

      >span:last-child {
        font-size: 10px;
        color: rgba(0, 0, 0, 0.35);
        margin-left: 3px;
      }
    }
  }

  .divider {
    width: 1px;
    height: 32px;
    background: rgba(232, 234, 236, 1);
    margin: 0;
  }
}

/* 库存明细标题 */
.leftHeader {
  margin: 16px 0;

  div {
    font-size: 15px;
    color: #1d252f;
    padding-left: 8px;
    border-left: 5px solid #41a772;
  }
}



/* 右侧：图表区域 */
.drawRight {
  width: 60%;
  border-radius: 4px;
  background: #f8f8f8;
  /* 背景色f8f8f8 */
  padding: 16px;
  /* 内部padding 16px */
  display: flex;
  flex-direction: column;
  gap: 14px;
  /* 子元素间距16px */
  height: 100%;
  /* 与drawLeft等高 */
  box-sizing: border-box;
  /* 避免padding撑大高度 */
}

/* 右侧图表容器（白色背景） */
.chart-container {
  background: #fff;
  /* 内容区域白色 */
  padding: 16px;
  /* 容器内边距16px */
  flex: 1;
  /* 平分高度 */
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}


// .drawRight .chart-container:first-child { height: 45%; }
.pie-charts {
  display: flex;
  height: 50%;
  /* 父级高度的 55% */
  min-height: 0;

  /* 关键：允许继续压缩 */
  .chartTitle {
    font-family: PingFang SC;
    font-weight: 500;
    font-style: Medium;
    font-size: 14px;
    leading-trim: NONE;
    line-height: 100%;
    letter-spacing: 0%;
    text-align: center;
    vertical-align: middle;
    color: #313D4B;
  }
}

.pie-charts .chart-container {
  flex: 1;
  height: 100%;
  /* 已有 */
  min-height: 0;
  /* 已有 */
  box-sizing: border-box;
  /* 下面这一行保证绝对等高 */
  align-self: stretch;
  /* 关键：强制同一行 flex item 高度拉满 */
}

.chart {
  width: 100%;
  flex: 1;
  min-height: 0;
  /* 关键：允许继续压缩，避免 echarts 计算高度被截断 */
}
</style>














<!-- 
<template>
  <div class="app-container">
    <div class="tops">
      <div v-for="(value, index) in lists" :key="index" class="list">
        <div class="list_left">
          <div>{{ value.name }}</div>
          <div>
            <span>{{ value.num }}</span>
            <span>{{ value.unit }}</span>
          </div>
        </div>
        <div class="list_right">
          <img :src="value.imgs" alt="">
        </div>
      </div>
    </div>
    <div class="centers">
      <div class="titles">
        <div v-for="(value, index) in titleLists" :class="index == selectIndexs ? 'selectIndex' : ''" :key="index"
          class="titleLists" @click="changeSearchs(index)">
          {{ value }}
        </div>
      </div>
      <div class="searchParams">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
          <el-form-item label="仓库名称" prop="warehouseName">
            <el-select style="width: 250px;" v-model="queryParams.warehouseCode">
              <el-option v-for="(value, index) in warehouseData" :key="index" :label="value.warehouseName"
                :value="value.warehouseCode"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备件名称" prop="warehouseName">
            <el-input style="width: 250px;" v-model="queryParams.warehouseName" placeholder="请输入" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="备件编码" prop="orderNo">
            <el-input style="width:250px;" v-model="queryParams.orderNo" placeholder="请输入" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="drawFooter" v-if="selectIndexs == 0">
        <div class="drawLeft">
          <div class="stock-container">
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/dqkc.png" alt="当前库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">当前库存</div>
                <div class="stock-value">
                  <span>{{ totalStock }}</span>
                  <span>台</span>
                </div>
              </div>
            </div>
            <div class="divider"></div>
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/aqkc.png" alt="安全库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">安全库存</div>
                <div class="stock-value"> <span>{{ totalSafeStock }}</span><span>台</span></div>
              </div>
            </div>
          </div>
          <div class="leftHeader">
            <div>库存明细</div>
          </div>
          <div class="leftTableWrap">
            <el-table :data="inventoryTableData" size="small" :max-height="rightHeight">
              <el-table-column prop="partName" label="备件名称" min-width="120" :show-overflow-tooltip="true"
                key="partName"></el-table-column>
              <el-table-column prop="realStock" key="realStock" label="在库数量" align="center"></el-table-column>
              <el-table-column prop="safeStock" key="safeStock" label="安全库存" align="center"></el-table-column>
              <el-table-column prop="status" label="状态" align="center" key="status">
                <template slot-scope="scope">
                  <div v-if="scope.row.status == 0">正常</div>
                  <div v-if="scope.row.status == 1">缺货</div>
                </template>
              </el-table-column>
            </el-table>
          </div>

        </div>

        <div class="drawRight">
          <div class="chart-container">
            <div ref="barChart" class="chart"></div>
          </div>
          <div class="pie-charts">
            <div class="chart-container">
              <div ref="pieChart1" class="chart"></div>
              <div class="chartTitle">各型号备件数量</div>
            </div>
            <div class="chart-container">
              <div ref="pieChart2" class="chart"></div>
              <div class="chartTitle">各型号备件数量</div>
            </div>
          </div>
        </div>
      </div>

      <div class="drawFooter" v-if="selectIndexs == 1">
        <div class="drawLeft">
          <div class="stock-container">
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/dqkc.png" alt="当前库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">领用数</div>
                <div class="stock-value">
                  <span>{{ totalcount }}</span>
                  <span>台</span>
                </div>
              </div>
            </div>
            <div class="divider"></div>
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/aqkc.png" alt="安全库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">领用总金额</div>
                <div class="stock-value"> <span>{{ totalamount }}</span><span>万元</span></div>
              </div>
            </div>
          </div>
          <div class="leftHeader">
            <div>领用明细</div>
          </div>
          <div class="leftTableWrap">
            <el-table :data="inventoryTableData1" size="small" :max-height="rightHeight">
              <el-table-column prop="deptname" min-width="120" :show-overflow-tooltip="true" label="部门名称" align="center"
                key="deptname1"></el-table-column>
              <el-table-column prop="username" key="username1" label="领用人" align="center"></el-table-column>
              <el-table-column prop="totalquantity" key="totalquantity1" label="领用数量" align="center"> </el-table-column>
              <el-table-column prop="totalamount" key="totalamount1" label="领用金额" align="center"> </el-table-column>
              <el-table-column prop="usetimes" key="usetimes1" label="领用次数" align="center"></el-table-column>
            </el-table>
          </div>
        </div>
        <div class="drawRight">
          <div class="chart-container">
            <div ref="barChart1" class="chart"></div>
          </div>
          <div class="pie-charts">
            <div class="chart-container">
              <div ref="pieChart3" class="chart"></div>
              <div class="chartTitle">各部门领用数量</div>
            </div>
            <div class="chart-container">
              <div ref="pieChart4" class="chart"></div>
              <div class="chartTitle">各部门领用金额</div>
            </div>
          </div>
        </div>
      </div>


      <div class="drawFooter" v-if="selectIndexs == 2">
        <div class="drawLeft">
          <div class="stock-container">
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/dqkc.png" alt="当前库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">入库数</div>
                <div class="stock-value">
                  <span>{{ totalcount1 }}</span>
                  <span>台</span>
                </div>
              </div>
            </div>
            <div class="divider"></div>
            <div class="stock-card">
              <div class="icon-wrapper">
                <img src="../assets/images/aqkc.png" alt="安全库存图标" class="stock-icon" />
              </div>
              <div class="text-content">
                <div class="stock-label">入库总金额</div>
                <div class="stock-value"> <span>{{ totalamount1 }}</span><span>万元</span></div>
              </div>
            </div>
          </div>
          <div class="leftHeader">
            <div>入库明细</div>
          </div>
          <div class="leftTableWrap">
            <el-table :data="inventoryTableData2" size="small" :max-height="rightHeight">
              <el-table-column prop="partname" label="备件名称" min-width="120" :show-overflow-tooltip="true"
                key="partname2"></el-table-column>
              <el-table-column prop="quantity" key="quantity12" label="数量" align="center"></el-table-column>
              <el-table-column prop="unitprice" key="unitprice2" label="单价" align="center"></el-table-column>
              <el-table-column prop="totalprice" key="totalprice2" label="总价" align="center"></el-table-column>
            </el-table>
          </div>
        </div>
        <div class="drawRight">
          <div class="chart-container">
            <div ref="barChart2" class="chart"></div>
          </div>
          <div class="pie-charts">
            <div class="chart-container">
              <div ref="pieChart5" class="chart"></div>
              <div class="chartTitle">入库数量</div>
            </div>
            <div class="chart-container">
              <div ref="pieChart6" class="chart"></div>
              <div class="chartTitle">入库总金额</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import zksl from '../assets/images/zksl.png'
import zkze from '../assets/images/zkze.png'
import zqk from '../assets/images/zqk.png'
import lysl from '../assets/images/lysl.png'
import { warehouseLists } from '@/api/select.js'
import * as echarts from 'echarts';
// import { inSummary, modelQuantityPie, modelAmountPie, inProductStat, detailSimple, homesummary, deptcount, deptamount, productstat, homedetail, distributionstock, distributionassets, totalStocks, totalSafeStocks, totalQuantity, stockcount, stockamount, stockgap, getPartStats, getpartList } from '@/api/home.js'
import * as API from '@/api/home.js'   // 统一收拢 api

const PIE_GRAD = [
  [{ offset: 0, color: '#FAB2FF' }, { offset: 1, color: '#5644FF' }],
  [{ offset: 0, color: '#FEA492' }, { offset: 1, color: '#FF4C52' }],
  [{ offset: 0, color: '#7AECF8' }, { offset: 1, color: '#48DE94' }],
  [{ offset: 0, color: '#A5A1FF' }, { offset: 1, color: '#1F90FF' }]
]
function buildPieOption (data, unit) {
  const showData = data.map((d, i) => {
    const color = i < 4
      ? { type: 'linear', x: 0, y: 1, x2: 0, y2: 0, colorStops: PIE_GRAD[i] }
      : ['#FFDD65', '#B37FEB', '#4ECBFF'][i - 4]
    return { ...d, itemStyle: { color } }
  })
  return {
    tooltip: { trigger: 'item', formatter: `{b}: {c}${unit}` },
    legend: { show: false },
    series: [{
      type: 'pie',
      radius: ['0%', '70%'],
      data: showData,
      label: { show: true, position: 'outside', formatter: `{b}\n{c}${unit}`, fontSize: 11, lineHeight: 14 },
      labelLine: { length: 10, length2: 15 }
    }]
  }
}

/* ----------------------------------------------------------
 * 工具函数： 柱状图 option 工厂（与原 option 完全一致）
 * ---------------------------------------------------------- */
function buildBarOption (xData, barArr, lineArr, legend, barName, lineName) {
  return {
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    legend: {
      data: legend,
      textStyle: { fontSize: 12 },
      center: 'center',
      top: 0,
      icon: 'circle',
      itemWidth: 12,
      itemHeight: 12
    },
    grid: { left: '5%', right: '5%', bottom: '0%', top: '20%', containLabel: true },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: { fontSize: 10, interval: 0 }
    },
    yAxis: [
      { type: 'value', name: '件', min: 0, max: 2500, interval: 500, axisLabel: { fontSize: 10 } },
      {
        type: 'value',
        name: '万元',
        min: 0,
        max: 500,
        interval: 50,
        position: 'right',
        axisLabel: { fontSize: 10 },
        axisLine: { show: false }
      }
    ],
    series: [
      {
        name: barName,
        type: 'bar',
        data: barArr,
        barWidth: 14,
        itemStyle: {
          borderRadius: [20, 20, 0, 0],
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: '#C8AEFC' },
              { offset: 1, color: '#9463F7' }
            ]
          }
        }
      },
      {
        name: lineName,
        type: 'line',
        yAxisIndex: 1,
        data: lineArr,
        lineStyle: { color: '#20C997', width: 2 },
        symbol: 'none',
        itemStyle: { color: '#20C997' }
      }
    ]
  }
}
export default {
  name: 'homeIndex',
  data () {
    return {
      /* 所有 data 字段保持与原文件完全一致，仅把重复字面量抽离 */
      inventoryTableData2: [],
      totalcount1: 0,
      totalamount1: 0,
      inventoryTableData1: [],
      totalSafeStock: 0,
      totalStock: 0,
      selectIndexs: 0,
      rightHeight: 0,
      inventoryTableData: [],
      barChartData2: { months: [], stockTotal: [], assetTotal: [] },
      barChartData1: { months: [], stockTotal: [], assetTotal: [] },
      barChartData: { months: [], stockTotal: [], assetTotal: [] },
      pieChartData2: [
        { name: '各型号入库数量', data: [], unit: '台' },
        { name: '各型号入库金额', data: [], unit: '万元' }
      ],
      pieChartData1: [
        { name: '各部门领用数量', data: [], unit: '台' },
        { name: '各部门领用金额', data: [], unit: '万元' }
      ],
      pieChartData: [
        { name: '各型号备件数量', data: [], unit: '台' },
        { name: '各型号备件金额', data: [], unit: '万元' }
      ],
      warehouseData: [],
      queryParams: {},
      titleLists: ['库存分析', '领用分析', '入库分析'],
      lists: [
        { name: '在库数量', num: 100, unit: '台', imgs: zksl },
        { name: '在库总额', num: 100, unit: '万元', imgs: zkze },
        { name: '总缺口', num: 100, unit: '台', imgs: zqk },
        { name: '领用数量', num: 100, unit: '台', imgs: lysl }
      ],
      totalcount: 0,
      totalamount: 0
    }
  },
  created () {
    this.loadWarehouseData()
    this.partList()
    /* 顶部四个卡片数据 */
    API.stockcount().then(res => { this.lists[0].num = res.data })
    API.stockamount().then(res => { this.lists[1].num = res.data })
    API.stockgap().then(res => { this.lists[2].num = res.data })
    API.totalQuantity().then(res => { this.lists[3].num = res.data })
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.calcHeight)
  },
  mounted () {
    this.$nextTick(() => {
      this.initBarChart()
      this.initPieCharts()
      this.calcHeight()
      this.gettotalStock()
      this.gettotalSafeStocks()
      window.addEventListener('resize', this.calcHeight)
    })
  },
  methods: {
    /* --------------------------------------------------
     *  下面所有方法仅做“合并重复代码”与“命名统一”，
     *  参数、返回值、触发事件与原版 100% 一致
     * -------------------------------------------------- */
    gettotalStock () {
      API.totalStocks(this.queryParams).then(res => { this.totalStock = res.data })
    },
    gettotalSafeStocks () {
      API.totalSafeStocks(this.queryParams).then(res => { this.totalSafeStock = res.data })
    },
    changeSearchs (index) {
      this.selectIndexs = index
      const map = [
        () => { this.initBarChart(); this.initPieCharts(); this.gettotalStock(); this.gettotalSafeStocks() },
        () => { this.gethomesummary(); this.gethomedetail(); this.initBarChart1(); this.initPieCharts1() },
        () => { this.getinSummary(); this.getdetailSimple(); this.initBarChart2(); this.initPieCharts2() }
      ]
      map[index]()
      this.calcHeight()
    },
    initBarChart2 () {
      API.inProductStat(this.queryParams).then(res => {
        const { months, assetTotal, stockTotal } = this.extractBar(res.data, 'partname', 'totalamount', 'totalcount')
        this.barChartData2 = { months, assetTotal, stockTotal }
        if (!this.$refs.barChart2) return
        const chart = echarts.init(this.$refs.barChart2)
        chart.setOption(buildBarOption(months, stockTotal, assetTotal, ['入库数量', '入库总额'], '入库总数', '入库总额'))
        window.addEventListener('resize', () => chart.resize())
      })
    },
    initPieCharts2 () {
      API.modelQuantityPie(this.queryParams).then(res => {
        this.pieChartData2[0].data = res.data.map(e => ({ name: e.model, value: e.totalcount }))
        this.drawPie('pieChart5', this.pieChartData2[0])
      })
      API.modelAmountPie(this.queryParams).then(res => {
        this.pieChartData2[1].data = res.data.map(e => ({ name: e.model, value: e.totalamount }))
        this.drawPie('pieChart6', this.pieChartData2[1])
      })
    },
    getdetailSimple () {
      API.detailSimple(this.queryParams).then(res => { this.inventoryTableData2 = res.data })
    },
    initPieCharts1 () {
      API.deptcount(this.queryParams).then(res => {
        this.pieChartData1[0].data = res.data.map(e => ({ name: e.deptname, value: e.totalcount }))
        this.drawPie('pieChart3', this.pieChartData1[0])
      })
      API.deptamount(this.queryParams).then(res => {
        this.pieChartData1[1].data = res.data.map(e => ({ name: e.deptname, value: e.totalamount }))
        this.drawPie('pieChart4', this.pieChartData1[1])
      })
    },
    gethomedetail () {
      API.homedetail(this.queryParams).then(res => { this.inventoryTableData1 = res.data })
    },
    getinSummary () {
      API.inSummary(this.queryParams).then(res => {
        this.totalcount1 = res.data.total_count
        this.totalamount1 = res.data.total_amount
      })
    },
    gethomesummary () {
      API.homesummary(this.queryParams).then(res => {
        this.totalcount = res.data.totalcount
        this.totalamount = res.data.totalamount
      })
    },
    initBarChart1 () {
      API.productstat(this.queryParams).then(res => {
        const { months, assetTotal, stockTotal } = this.extractBar(res.data, 'partname', 'totalamount', 'totalcount')
        this.barChartData1 = { months, assetTotal, stockTotal }
        if (!this.$refs.barChart1) return
        const chart = echarts.init(this.$refs.barChart1)
        chart.setOption(buildBarOption(months, stockTotal, assetTotal, ['领用数量', '领用总额'], '领用总数', '领用总额'))
        window.addEventListener('resize', () => chart.resize())
      })
    },
    partList () {
      API.getpartList(this.queryParams).then(res => { this.inventoryTableData = res.rows })
    },
    loadAllData () {
      this.changeSearchs(this.selectIndexs)
    },
    handleQuery () {
      this.loadAllData()
    },
    resetQuery () {
      this.queryParams = { warehouseCode: '', partName: '', partCode: '' }
      this.loadAllData()
    },
    calcHeight () {
      const drawRight = this.$el.querySelector('.drawRight')
      const titles = this.$el.querySelector('.titles')
      const search = this.$el.querySelector('.searchParams')
      let headH = 0
      if (titles) headH += titles.offsetHeight
      if (search) headH += search.offsetHeight
      this.rightHeight = drawRight.offsetHeight - headH - 32 /* pad*2 */
    },
    initBarChart () {
      API.getPartStats(this.queryParams).then(res => {
        const { months, assetTotal, stockTotal } = this.extractBar(res.data, 'part_name', 'total_price', 'total_quantity')
        this.barChartData = { months, assetTotal, stockTotal }
        if (!this.$refs.barChart) return
        const chart = echarts.init(this.$refs.barChart)
        chart.setOption(buildBarOption(months, stockTotal, assetTotal, ['库存总数', '资产总额'], '库存总数', '资产总额'))
        window.addEventListener('resize', () => chart.resize())
      })
    },
    initPieCharts () {
      API.distributionstock(this.queryParams).then(res => {
        this.pieChartData[0].data = res.data.map(e => ({ name: e.part_name, value: e.total_stock }))
        this.drawPie('pieChart1', this.pieChartData[0])
      })
      API.distributionassets(this.queryParams).then(res => {
        this.pieChartData[1].data = res.data.map(e => ({ name: e.part_name, value: e.total_price }))
        this.drawPie('pieChart2', this.pieChartData[1])
      })
    },
    loadWarehouseData () {
      warehouseLists().then(res => { this.warehouseData = res.rows || [] })
        .catch(() => this.$message.error('加载仓库数据失败'))
    },
    /* --------------------------------------------------
     *  下面是纯工具函数，不与业务耦合
     * -------------------------------------------------- */
    // 统一提取柱状图需要的三组数组
    extractBar (list, nameKey, amountKey, countKey) {
      return {
        months: list.map(item => item[nameKey]),
        assetTotal: list.map(item => item[amountKey]),
        stockTotal: list.map(item => item[countKey])
      }
    },
    // 绘制单个 pie 图（dom 名 + 配置对象）
    drawPie (ref, { data, unit }) {
      if (!this.$refs[ref]) return
      const ins = echarts.init(this.$refs[ref])
      ins.setOption(buildPieOption(data, unit))
      window.addEventListener('resize', () => ins.resize())
    }
  }}
</script>

<style scoped lang="scss">
/* 全局样式 */
.app-container {
  padding: 16px;
  background: #f5f5f5;
  // min-height: 100vh;
  height: 100%;
  box-sizing: border-box;
}

/* ==== 恢复原始样式：tops ==== */
.tops {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;

  .list {
    background: #fff;
    width: 25%;
    height: 92px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .list_right {
      width: 52px;
      height: 52px;
      margin-right: 39px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .list_left {
      margin-left: 49px;

      >div:first-child {
        font-family: PingFang SC;
        font-weight: 400;
        font-size: 14px;
        line-height: 22px;
        color: rgba(0, 0, 0, 0.6);
      }

      >div:last-child {
        margin-top: 4px;

        >span:first-child {
          font-weight: 500;
          font-size: 24px;
          color: rgba(29, 37, 47, 1);
        }

        >span:last-child {
          font-weight: 400;
          font-size: 14px;
          margin-left: 4px;
          color: rgba(0, 0, 0, 0.35);
        }
      }
    }
  }
}

/* ==== 恢复原始样式：centers ==== */
.centers {
  display: flex;
  margin-top: 16px;
  flex-direction: column;
  height: calc(100vh - 190px);
  background: #fff;
  width: 100%;
  padding: 16px 0;
  /* 恢复原始padding */
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .titles {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 296px;
    height: 38px;
    line-height: 38px;
    margin: 0 auto;
    background: rgba(244, 244, 246, 1);

    .titleLists {
      width: 92px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 15px;
      color: rgba(49, 61, 75, 1);
      cursor: pointer;
    }

    .selectIndex {
      background: #fff;
      color: rgba(65, 167, 114, 1);
      border-radius: 2px;
    }
  }

  .searchParams {
    margin: 22px 0;
    /* 恢复原始margin */
    padding: 0 24px;
  }
}

/* 核心区域：drawFooter（保持之前修改的无padding） */
.drawFooter {
  display: flex;
  gap: 16px;
  flex: 1;
  /* 占满父级剩余高度 */
  min-height: 0;
  /* 关键：允许继续压缩，防止溢出截断 */
  height: auto !important;
  /* 放弃之前的 calc 写法，交给 flex 控制 */

}

/* 左侧：库存明细 */
.drawLeft {
  width: 40%;
  background: #fff;
  padding: 0 16px 16px;
  display: flex;
  flex-direction: column;
  /* 关键 */
  height: 100%;
  /* 与右侧等高 */
  box-sizing: border-box;
}

.leftTableWrap {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.el-table {
  // flex: 1;                  /* 表格本身也 flex:1，自然撑高 */
  width: 100%;
}

/* 统计卡片 */
.stock-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f8f8f8;
  border-radius: 8px;
  padding: 12px 78px;

  .stock-card {
    flex: 0 0 auto;
    /* 不改变原有宽度 */
    display: flex;
    align-items: center;
  }

  .icon-wrapper {
    width: 28px;
    height: 28px;
    margin-right: 10px;
  }

  .text-content {
    margin-left: 5px;
    .stock-label {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.6);
    }

    .stock-value {
      margin-top: 4px;

      >span:first-child {
        font-size: 16px;
        color: #000;
      }

      >span:last-child {
        font-size: 10px;
        color: rgba(0, 0, 0, 0.35);
        margin-left: 3px;
      }
    }
  }

  .divider {
    width: 1px;
    height: 32px;
    background: rgba(232, 234, 236, 1);
    margin: 0;
  }
}

/* 库存明细标题 */
.leftHeader {
  margin: 16px 0;

  div {
    font-size: 15px;
    color: #1d252f;
    padding-left: 8px;
    border-left: 5px solid #41a772;
  }
}



/* 右侧：图表区域 */
.drawRight {
  width: 60%;
  border-radius: 4px;
  background: #f8f8f8;
  /* 背景色f8f8f8 */
  padding: 16px;
  /* 内部padding 16px */
  display: flex;
  flex-direction: column;
  gap: 14px;
  /* 子元素间距16px */
  height: 100%;
  /* 与drawLeft等高 */
  box-sizing: border-box;
  /* 避免padding撑大高度 */
}

/* 右侧图表容器（白色背景） */
.chart-container {
  background: #fff;
  /* 内容区域白色 */
  padding: 16px;
  /* 容器内边距16px */
  flex: 1;
  /* 平分高度 */
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}


// .drawRight .chart-container:first-child { height: 45%; }
.pie-charts {
  display: flex;
  height: 50%;
  /* 父级高度的 55% */
  min-height: 0;

  /* 关键：允许继续压缩 */
  .chartTitle {
    font-family: PingFang SC;
    font-weight: 500;
    font-style: Medium;
    font-size: 14px;
    leading-trim: NONE;
    line-height: 100%;
    letter-spacing: 0%;
    text-align: center;
    vertical-align: middle;
    color: #313D4B;
  }
}

.pie-charts .chart-container {
  flex: 1;
  height: 100%;
  /* 已有 */
  min-height: 0;
  /* 已有 */
  box-sizing: border-box;
  /* 下面这一行保证绝对等高 */
  align-self: stretch;
  /* 关键：强制同一行 flex item 高度拉满 */
}

.chart {
  width: 100%;
  flex: 1;
  min-height: 0;
  /* 关键：允许继续压缩，避免 echarts 计算高度被截断 */
}
</style>

-->